import { useState, useEffect, useCallback, useRef } from 'react';
import { invoke } from '@tauri-apps/api/core';

// 性能指标接口
export interface PerformanceMetrics {
  timestamp: number;
  cpu_usage: number;
  memory_usage: number;
  memory_total: number;
  disk_usage: number;
  network_rx: number;
  network_tx: number;
  process_count: number;
  uptime: number;
  custom_metrics: Record<string, number>;
}

// 性能事件接口
export interface PerformanceEvent {
  id: string;
  name: string;
  start_time: number;
  end_time?: number;
  duration?: number;
  metadata: Record<string, any>;
}

// 性能报告接口
export interface PerformanceReport {
  timestamp: number;
  uptime: number;
  avg_cpu_usage: number;
  avg_memory_usage: number;
  total_events: number;
  active_events_count: number;
  event_stats: Record<string, EventStats>;
  recent_metrics: PerformanceMetrics[];
  recent_events: PerformanceEvent[];
}

export interface EventStats {
  count: number;
  total_duration: number;
  avg_duration: number;
  min_duration: number;
  max_duration: number;
}

// 性能监控 Hook
export function usePerformanceMonitor(
  options: {
    autoStart?: boolean;
    interval?: number;
    maxHistory?: number;
  } = {}
) {
  const { autoStart = false, interval = 5000, maxHistory = 100 } = options;

  const [metrics, setMetrics] = useState<PerformanceMetrics | null>(null);
  const [history, setHistory] = useState<PerformanceMetrics[]>([]);
  const [isMonitoring, setIsMonitoring] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const intervalRef = useRef<number | null>(null);

  // 获取当前性能指标
  const collectMetrics = useCallback(async () => {
    try {
      const newMetrics = await invoke<PerformanceMetrics>(
        'get_performance_metrics'
      );
      setMetrics(newMetrics);

      setHistory(prev => {
        const updated = [...prev, newMetrics];
        return updated.slice(-maxHistory);
      });

      setError(null);
      return newMetrics;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      setError(errorMessage);
      throw err;
    }
  }, [maxHistory]);

  // 开始监控
  const startMonitoring = useCallback(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }

    setIsMonitoring(true);
    collectMetrics(); // 立即收集一次

    intervalRef.current = setInterval(() => {
      collectMetrics().catch(console.error);
    }, interval) as unknown as number;
  }, [collectMetrics, interval]);

  // 停止监控
  const stopMonitoring = useCallback(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
    setIsMonitoring(false);
  }, []);

  // 清除历史数据
  const clearHistory = useCallback(() => {
    setHistory([]);
  }, []);

  // 自动开始监控
  useEffect(() => {
    if (autoStart) {
      // 延迟一点启动，确保组件完全挂载
      const timer = setTimeout(() => {
        startMonitoring();
      }, 100);

      return () => {
        clearTimeout(timer);
        stopMonitoring();
      };
    }

    return () => {
      stopMonitoring();
    };
  }, [autoStart, startMonitoring, stopMonitoring]);

  // 组件挂载时立即收集一次数据
  useEffect(() => {
    collectMetrics().catch(console.error);
  }, []);

  return {
    metrics,
    history,
    isMonitoring,
    error,
    collectMetrics,
    startMonitoring,
    stopMonitoring,
    clearHistory,
  };
}

// 性能事件追踪 Hook
export function usePerformanceEvent() {
  const [activeEvents, setActiveEvents] = useState<
    Map<string, PerformanceEvent>
  >(new Map());
  const [completedEvents, setCompletedEvents] = useState<PerformanceEvent[]>(
    []
  );

  // 开始事件
  const startEvent = useCallback(
    async (name: string, metadata: Record<string, any> = {}) => {
      try {
        const eventId = await invoke<string>('start_performance_event', {
          name,
          metadata,
        });

        const event: PerformanceEvent = {
          id: eventId,
          name,
          start_time: Date.now(),
          metadata,
        };

        setActiveEvents(prev => new Map(prev).set(eventId, event));
        return eventId;
      } catch (error) {
        console.error('Failed to start performance event:', error);
        throw error;
      }
    },
    []
  );

  // 结束事件
  const endEvent = useCallback(async (eventId: string) => {
    try {
      const completedEvent = await invoke<PerformanceEvent | null>(
        'end_performance_event',
        { eventId }
      );

      if (completedEvent) {
        setActiveEvents(prev => {
          const updated = new Map(prev);
          updated.delete(eventId);
          return updated;
        });

        setCompletedEvents(prev => [completedEvent, ...prev].slice(0, 100));
        return completedEvent;
      }

      return null;
    } catch (error) {
      console.error('Failed to end performance event:', error);
      throw error;
    }
  }, []);

  // 测量函数执行时间
  const measure = useCallback(
    async <T>(
      name: string,
      fn: () => Promise<T> | T,
      metadata: Record<string, any> = {}
    ): Promise<T> => {
      const eventId = await startEvent(name, metadata);

      try {
        const result = await fn();
        await endEvent(eventId);
        return result;
      } catch (error) {
        await endEvent(eventId);
        throw error;
      }
    },
    [startEvent, endEvent]
  );

  return {
    activeEvents: Array.from(activeEvents.values()),
    completedEvents,
    startEvent,
    endEvent,
    measure,
  };
}

// 自定义指标 Hook
export function useCustomMetrics() {
  const setMetric = useCallback(async (name: string, value: number) => {
    try {
      await invoke('set_custom_metric', { name, value });
    } catch (error) {
      console.error('Failed to set custom metric:', error);
      throw error;
    }
  }, []);

  const incrementMetric = useCallback(
    async (name: string, value: number = 1) => {
      try {
        await invoke('increment_custom_metric', { name, value });
      } catch (error) {
        console.error('Failed to increment custom metric:', error);
        throw error;
      }
    },
    []
  );

  return {
    setMetric,
    incrementMetric,
  };
}

// 性能报告 Hook
export function usePerformanceReport() {
  const [report, setReport] = useState<PerformanceReport | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const generateReport = useCallback(async () => {
    setLoading(true);
    setError(null);

    try {
      const newReport = await invoke<PerformanceReport>(
        'get_performance_report'
      );
      setReport(newReport);
      return newReport;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const clearData = useCallback(async () => {
    try {
      await invoke('clear_performance_data');
      setReport(null);
    } catch (error) {
      console.error('Failed to clear performance data:', error);
      throw error;
    }
  }, []);

  return {
    report,
    loading,
    error,
    generateReport,
    clearData,
  };
}

// React 性能测量 Hook
export function useRenderPerformance(componentName: string) {
  const renderStartTime = useRef<number>(Date.now());
  const { measure } = usePerformanceEvent();

  useEffect(() => {
    const startTime = renderStartTime.current;
    const endTime = Date.now();
    const duration = endTime - startTime;

    // 只记录超过阈值的渲染时间
    if (duration > 16) {
      // 超过一帧的时间
      measure(`render:${componentName}`, () => Promise.resolve(), {
        duration,
        component: componentName,
        type: 'render',
      }).catch(console.error);
    }
  });

  // 更新开始时间为下次渲染做准备
  renderStartTime.current = Date.now();
}

// 网络请求性能测量
export function useNetworkPerformance() {
  const { measure } = usePerformanceEvent();

  const measureRequest = useCallback(
    async <T>(url: string, requestFn: () => Promise<T>): Promise<T> => {
      return measure(`network:${url}`, requestFn, {
        url,
        type: 'network',
      });
    },
    [measure]
  );

  return { measureRequest };
}

// 内存使用监控
export function useMemoryMonitor(threshold: number = 100 * 1024 * 1024) {
  // 100MB 默认阈值
  const [memoryWarning, setMemoryWarning] = useState(false);
  const { metrics } = usePerformanceMonitor({
    autoStart: true,
    interval: 10000,
  });

  useEffect(() => {
    if (metrics && metrics.memory_usage > threshold) {
      setMemoryWarning(true);
    } else {
      setMemoryWarning(false);
    }
  }, [metrics, threshold]);

  return {
    memoryWarning,
    currentMemory: metrics?.memory_usage || 0,
    memoryPercentage: metrics
      ? (metrics.memory_usage / metrics.memory_total) * 100
      : 0,
  };
}
